package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

public class BeanUtil {

	public static void copyProperties(Object source, Object target) {
		BeanUtils.copyProperties(source, target);
	}


	public static String[] getNullPropertyNames(Object source) {
		final BeanWrapper src = new BeanWrapperImpl(source);
		java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

		Set<String> emptyNames = new HashSet<String>();
		for (java.beans.PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if (srcValue == null) {
				emptyNames.add(pd.getName());
			}
		}
		String[] result = new String[emptyNames.size()];
		return emptyNames.toArray(result);
	}

	/**
	 * 拷贝不为空的值
	 */
	public static void copyPropertiesIgnoreNull(Object src, Object target) {
		BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
	}



	/**
	 * 转换Bean为Map
	 */
	public static <T> Map<String, Object> beanToMap(Object obj) {
		Map<String, Object> map = new HashMap<>();
		BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
		PropertyDescriptor[] descriptor = beanWrapper.getPropertyDescriptors();
		for (PropertyDescriptor aDescriptor : descriptor) {
			String name = aDescriptor.getName();
			if (!"class".equals(name)) {
				map.put(name, beanWrapper.getPropertyValue(name));
			}
		}

		return map;
	}



	/**
	 * Bean对象转JSON
	 *
	 * @param object
	 * @param dataFormatString
	 * @return
	 */
	public static String beanToJson(Object object, String dataFormatString) {
		if (object != null) {
			if (StringUtils.isEmpty(dataFormatString)) {
				return JSONObject.toJSONString(object);
			}
			return JSON.toJSONStringWithDateFormat(object, dataFormatString);
		} else {
			return null;
		}
	}

	/**
	 * Bean对象转JSON
	 *
	 * @param object
	 * @return
	 */
	public static String beanToJson(Object object) {
		if (object != null) {
			return JSON.toJSONString(object);
		} else {
			return null;
		}
	}

	/**
	 * String转JSON字符串
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public static String stringToJsonByFastjson(String key, String value) {
		if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
			return null;
		}
		Map<String, String> map = new HashMap<String, String>(16);
		map.put(key, value);
		return beanToJson(map, null);
	}

	/**
	 * 将json字符串转换成对象
	 *
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static Object jsonToBean(String json, Object clazz) {
		if (StringUtils.isEmpty(json) || clazz == null) {
			return null;
		}
		return JSON.parseObject(json, clazz.getClass());
	}

	/**
	 * json字符串转map
	 *
	 * @param json
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> jsonToMap(String json) {
		if (StringUtils.isEmpty(json)) {
			return null;
		}
		return JSON.parseObject(json, Map.class);
	}

	/**
	 * 过滤集合中的空对象
	 *
	 * @param objList
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> filterEmptyObj(List<T> objList, Class<T> clazz) {
		return objList.parallelStream().filter(n -> {
			Boolean flag = false;
			try {
				BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
				PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
				for (PropertyDescriptor pd : pds) {
					Method readMethod = pd.getReadMethod();
					Object ret = readMethod.invoke(n);
					if (pd.getPropertyType().equals(String.class)) {
						if (!StringUtils.isEmpty(ret)) {
							flag = true;
						}
					} else {
						if (!ObjectUtils.isEmpty(ret)) {
							flag = true;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return flag;
		}).collect(Collectors.toList());
	}

	/**
	 * 对象属性中的""设置成null
	 *
	 * @param t
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T changeEmpty2Null(T t, Class<T> clazz) {
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor pd : pds) {
				Method readMethod = pd.getReadMethod();
				Object ret = readMethod.invoke(t);
				if (pd.getPropertyType().equals(String.class)) {
					if ("".equals(ret)) {
						Method writeMethod = pd.getWriteMethod();
						writeMethod.invoke(t, new Object[]{null});
					}
				}
			}
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 对象属性中的null设置成""
	 *
	 * @param t
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T changeNull2Empty(T t, Class<T> clazz) {
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor pd : pds) {
				Method readMethod = pd.getReadMethod();
				Object ret = readMethod.invoke(t);
				if (pd.getPropertyType().equals(String.class)) {
					if (ret == null) {
						Method writeMethod = pd.getWriteMethod();
						writeMethod.invoke(t, new Object[]{""});
					}
				}
			}
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 判断对象中所有字段是否为NULL
	 *
	 * @param obj
	 * @return boolean
	 */
	public static boolean isAllFieldNull(Object obj) {
		boolean flag = false;
		try {
			// 得到类对象
			Class stuCla = (Class) obj.getClass();
			//得到属性集合
			Field[] fs = stuCla.getDeclaredFields();
			flag = true;
			//遍历属性
			for (Field f : fs) {
				// 设置属性是可以访问的(私有的也可以)
				f.setAccessible(true);
				// 得到此属性的值
				Object val = f.get(obj);
				//只要有1个属性不为空,那么就不是所有的属性值都为空
				if (val != null) {
					flag = false;
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 生成Token Token：Nv6RRuGEVvmGjB+jimI/gw==
	 *
	 * @return
	 */
	public static String makeToken() {
		String token = UUID.randomUUID().toString().replaceAll("-", "") + "";
		// 数据指纹 128位长 16个字节 md5
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte md5[] = md.digest(token.getBytes());
			// base64编码--任意二进制编码明文字符 adfsdfsdfsf
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
}
